package com.cracker.websocket.server.service;

import com.cracker.websocket.server.constant.MessageTypeConstant;
import com.cracker.websocket.server.dto.StatInfoDto;
import com.cracker.websocket.server.dto.message.GroupMessageDto;
import com.cracker.websocket.server.dto.messagemeta.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Set;

@Service
@Slf4j
public class GmService {
    @Autowired
    private SessionService sessionService;
    @Autowired
    private ChatRoomService chatRoomService;
    @Autowired
    private StatService statService;
    @Autowired
    private GroupService groupService;

    public void kickOut(int userId) throws IOException {
        Session session = sessionService.getByUserId(userId);
        if (null != session) {
            session.close();
        }
    }

    public void chatRoomBroadcast(String msg, String chatRoomId) {
        Set<Session> sessions = chatRoomService.listSessionByRoomId(chatRoomId);
        int count = 0;
        if (null != sessions) {
            try {
                for (Session session : sessions) {
                    session.getBasicRemote().sendText(msg);
                    count++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.warn("广播:{} 聊天室id:{}, 接收用户数量:{}", msg, chatRoomId, count);
    }

    public void sendMsg(int id, String msg) throws IOException {
        Session session = sessionService.getByUserId(id);
        session.getBasicRemote().sendText(msg);
    }

    /**
     * 读取在线信息统计
     */
    public StatInfoDto getOnlineInfo() {
        StatInfoDto statInfoDto = new StatInfoDto();
        statInfoDto.setMaxOnlineCount(statService.getMaxOnlineCount());
        statInfoDto.setOnlineCount(statService.getOnlineCount());
        return statInfoDto;
    }

    public void groupBroadcast(String msg, String groupId) throws IOException {
        GroupMessageDto<TextMessage> messageDto = new GroupMessageDto<>();
        TextMessage textMessage = new TextMessage();
        textMessage.setContent(msg);
        messageDto.setMessage(textMessage);
        messageDto.setMessageType(MessageTypeConstant.TEXT);
        groupService.broadcast(null, groupId, messageDto);
    }
}
